<template>
  <page-view class="login">
    <page-header title="登录" :show-back="true"></page-header>
    <div class="content-box">
      <van-form @submit="onSubmit">
        <van-cell-group inset>
          <van-field
            v-model="user_phone"
            name="user_phone"
            label="用户名"
            placeholder="用户名"
            :rules="[
              {
                pattern: /^1([358][0-9]|4[79])[0-9]{8}$/,
                message: '账户不匹配',
              },
            ]"
          />
          <!-- validator 通过函数进行校验，可以返回一个 Promise 来进行异步校验 -->
          <!-- pattern 通过正则表达式进行校验，正则无法匹配表示校验不通过 -->
          <van-field
            v-model="password"
            type="password"
            name="password"
            label="密码"
            placeholder="密码"
            :rules="[{ validator: validatorPassword }]"
          />
        </van-cell-group>
        <Drag @unlock="unlock" />
        <div style="margin: 16px">
          <van-button
            round
            block
            type="primary"
            native-type="submit"
            :loading="isLoading"
            loading-text="登录中"
            :disabled="isLoading"
          >
            提交
          </van-button>
        </div>
      </van-form>
      <div class="tips">
        还没有账号？去
        <router-link :to="{ name: 'Register' }">注册</router-link>
      </div>
    </div>
  </page-view>
</template>

<script setup>
import { ref } from "vue";
import { Toast } from "vant";
import { useStore } from "vuex";
import Api from "../utils/api";
import { useRouter, useRoute } from "vue-router";
import MD5 from "md5.js";
import Drag from "../components/Drag.vue";
const store = useStore();
const router = useRouter();
const route = useRoute();
const user_phone = ref("");
const password = ref("");
const isLoading = ref(false);

// 滑块解锁
const clock = ref(false);
function unlock() {
  clock.value = true;
}

// 提交事件
const onSubmit = (values) => {
  // 先解锁
  if (clock.value === false) {
    Toast.clear(true);
    Toast.fail("请先解锁");
    return;
  }
  // 密码装饰
  values.password = new MD5().update(values.password).digest("hex");
  console.log("submit", values);
  Toast.loading("正在登录");
  isLoading.value = true;
  // 为了有延迟效果
  setTimeout(async () => {
    try {
      // 账号密码通过api验证返回用户信息和一个token
      let results = await Api.userInfo.login(values);
      // 返回的数据添加进vuex仓库
      store.commit("setUserInfo", results.user_info);
      store.commit("setToken", results.token);
      // console.log(store.userInfo);
      Toast.clear(true);
      Toast.success("登录成功");
      if (route.query.redirect) {
        router.push(route.query.redirect);
      } else {
        router.back();
      }
    } catch (error) {
      console.log(error);
    } finally {
      isLoading.value = false;
    }
  }, 1000);
};

// 函数验证
const validatorPassword = (val) => {
  if (val.trim() === "") {
    return "密码不能为空";
  } else if (val.length < 6 || val.length > 18) {
    return "密码长度应在6-18之间";
  }
};
</script>

<style lang="scss" scoped>
.login {
  .content-box {
    flex: 1;
    overflow: auto;
    .tips {
      @include flexbox(row, center, center);
      a {
        color: skyblue;
      }
    }
  }
}
</style>